<template>
  <div>
    <van-nav-bar
      title="新增收款信息"
      left-arrow
      left-text="返回"
      @click-left="$emit('close')"
    />
    <van-form ref="submitForm" @submit="doSubmit">
      <van-field
        readonly
        clickable
        name="receiptDate"
        :value="submitForm.receiptDate"
        label="日期选择"
        placeholder="点击选择日期"
        input-align="left"
        :rules="[{ required: true, message: '请选择日期' }]"
        @click="showReceiptDate = true"
      />
      <van-field
        v-model="submitForm.customerName"
        readonly
        clickable
        name="customerName"
        label="客户名称"
        placeholder="点击选择客户"
        input-align="left"
        :rules="[{ required: true, message: '请选择客户' }]"
        @click="showCustomer=true"
      />
      <dict-select
        v-model="submitForm.receiptMethod"
        label="付款方式"
        dict-key="payment_method"
        @input="handleChangePaymentMethod"
      />
      <van-row v-if="submitForm.dataList">
        <van-swipe-cell v-for="(item,index) in submitForm.dataList" :key="index">
          <van-divider content-position="left" :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">{{ `订单${index+1}` }}</van-divider>
          <van-cell-group inset>
            <van-cell title="产品" title-class="cell_value">
              <template #title>
                {{ item.productName }}*{{ item.orderQuantity }}{{ item.unit }}
              </template>
              <template #label>
                共{{ item.orderAmount }}元
              </template>
            </van-cell>
            <van-cell title="已收款" :value="item.paidAmount">
              <template #label>
                <span>剩余待收款{{ item.remainingAmount }}</span>
              </template>
            </van-cell>
            <van-field
              v-model="item.amount"
              name="amount"
              label="收款金额"
              type="number"
              placeholder="请输入收款金额"
              :rules="[{ required: true, message: '' }]"
              input-align="left"
            />
            <van-field
              v-model="item.remark"
              rows="1"
              autosize
              label="备注"
              type="textarea"
              maxlength="100"
              show-word-limit
              placeholder="请输入备注"
              input-align="left"
            />
          </van-cell-group>
          <template #right>
            <van-button class="swipe_button" square type="danger" text="删除" @click="doDelete(index)" />
          </template>
        </van-swipe-cell>
      </van-row>
      <van-button style="margin-bottom: 10px" icon="plus" plain block native-type="button" @click="doShowOrder">添加订单</van-button>
      <div style="margin: 16px;">
        <van-button round block type="danger" native-type="submit">提交</van-button>
      </div>
    </van-form>
    <div v-if="showCustomer">
      <select-customer ref="selectCustomer" :visible="showCustomer" @close="handleCloseCustomer" />
    </div>
    <div v-if="showOrder">
      <select-order ref="selectOrder" multiple :disable-ids="submitForm.orderIds" :visible="showOrder" @close="handleCloseOrder" />
    </div>
    <van-calendar v-model="showReceiptDate" :min-date="minDate" :show-confirm="false" @confirm="onConfirmReceiptDate" />
  </div>
</template>

<script>
import DictSelect from '@/components/dictSelect.vue'
import SelectCustomer from '@/components/modules/selectCustomer.vue'
import SelectOrder from '@/components/modules/selectOrder.vue'
import { saveBatchReceipt } from '@/api/receipt'
import { Dialog, Toast } from 'vant'
import moment from 'moment'
import Moment from 'moment/moment'

export default {
  name: 'ReceiptBatchSubmitModule',
  components: { SelectOrder, SelectCustomer, DictSelect },
  data() {
    return {
      showReceiptDate: false,
      showCustomer: false,
      showOrder: false,
      submitForm: {},
      orderInfo: {},
      minDate: moment(new Date()).subtract(30, 'years').toDate()
    }
  },
  methods: {
    init() {
      this.resetForm()
    },
    resetForm() {
      this.orderInfo = {}
      this.submitForm = { id: '', customerId: '', orderIds: [], dataList: [] }
    },
    doSubmit() {
      if (!this.submitForm.dataList || this.submitForm.dataList.length === 0) {
        Toast.fail('请选择订单')
        return
      }
      saveBatchReceipt(this.submitForm).then(resp => {
        if (resp.success) {
          this.$toast.success('操作成功')
          this.$emit('close')
        }
      })
    },
    handleChangePaymentMethod(val) {
      this.submitForm.receiptMethod = val
    },
    doShowOrder() {
      if (!this.submitForm.customerId || this.submitForm.customerId === '') {
        Toast.fail('请先选择客户')
        return
      }
      this.showOrder = true
      this.$nextTick(() => {
        this.$refs.selectOrder.handleSearch(
          { customerId: this.submitForm.customerId,
            paymentStateList: ['0', '1'],
            orderStateList: ['0', '1', '2']
          })
      })
    },
    onConfirmReceiptDate(row) {
      this.submitForm.receiptDate = Moment(row).format('YYYY-MM-DD')
      this.showReceiptDate = false
    },
    handleCloseCustomer(row) {
      this.showCustomer = false
      if (row) {
        this.submitForm.customerId = row.id
        this.submitForm.customerName = row.customerName
      }
    },
    handleCloseOrder(dataList) {
      this.showOrder = false
      if (dataList && dataList.length > 0) {
        for (let i = 0; i < dataList.length; i++) {
          const row = dataList[i]
          const data = {
            orderQuantity: row.quantity,
            productName: row.productName,
            unit: row.unit,
            orderAmount: row.amount,
            paidAmount: row.paidAmount,
            remainingAmount: row.remainingAmount,
            quantity: 0,
            orderId: row.id,
            remark: ''
          }
          if (this.submitForm.customerId && this.submitForm.customerId !== row.customerId) {
            this.$toast.fail('只能选择相同客户的订单')
            return
          }
          if (this.submitForm.orderIds.length > 0 && this.submitForm.orderIds.indexOf(row.orderId) !== -1) {
            this.$toast.fail(`选择订单与第${this.submitForm.orderIds.indexOf(row.orderId) + 1}条订单重复`)
            return
          }
          this.submitForm.orderIds.push(data.orderId)
          this.submitForm.dataList.push(data)
        }
      }
    },
    getContainer() {
      return document.body
    },
    checkNumberGreaterThanZero(value) {
      return value > 0
    },
    doDelete(index) {
      Dialog.confirm({
        title: '删除订单确认',
        message: '是否从此收款单中移除此订单'
      }).then(() => {
        this.submitForm.orderIds.splice(index, 1)
        this.submitForm.dataList.splice(index, 1)
      })
    }
  }
}
</script>

<style scoped>

</style>
